package com.cet.qz.unit01.chapter1_2;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-07 20:52
 **/
public class Qz1_2_18 {

    public static void main(String[] args) {
        Accumulator accumulator = new Accumulator();
        accumulator.addDataValue(1);
        accumulator.addDataValue(2);
        accumulator.addDataValue(3);
        accumulator.addDataValue(4);
        accumulator.addDataValue(5);
        System.out.println("样本均值为："+accumulator.mean());
        System.out.println("样本方差为："+accumulator.var());
    }
}

class Accumulator{
    private double m = 0.0;
    private double s = 0.0;
    private int N = 0;

    public Accumulator() {
    }

    public void addDataValue(double x) {
        N++;
        s = s + 1.0 * (N-1)/N * (x - m) * (x - m);
        m = m + (x -m)/N;
    }

    //样本均值
    public double mean() {
        return m;
    }

    //样本方差
    public double var() {
        return s/(N -1);
    }

    //标准差
    public double stddev() {
        return Math.sqrt(this.var());
    }
}
